package com.tianma.springcloud.controller;

import com.tianma.springcloud.pojo.Dept;
import com.tianma.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author lgc
 * @createDate 2020/9/1 - 15:28
 */
@RestController
public class DeptContrioller {

    @Autowired
    private DeptService deptService;
    @Autowired
    private DiscoveryClient client;

    @PostMapping("/dept/add")
    public boolean addDept(Dept dept){
        System.out.println("dept = " + dept);
        return deptService.addDept(dept);
    }

    @GetMapping("/dept/get/{id}")
    public Dept getDeptById(@PathVariable("id") Long id){
        Dept dept = deptService.queryById(id);
        if (dept==null){
            throw new RuntimeException("没有该对象");
        }
        return deptService.queryById(id);
    }

    @GetMapping("/dept/list")
    public List<Dept> getDeptAll(){
        return deptService.queryAll();
    }

    @GetMapping("/dept/client")
     public Object discovery(){
         List<String> services = client.getServices();
         System.out.println("services = " + services);
         List<ServiceInstance> instances = client.getInstances(services.get(0));
         for (ServiceInstance instance : instances) {
             System.out.println(
                     instance.getHost()+"\t"+
                     instance.getPort()+"\t"+
                     instance.getUri()+"\t"+
                     instance.getServiceId()
             );

         }
         return client;
     }
}
